<template>
  <el-select
    v-model="value"
    multiple
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="TestRemoteMethod"
    value-key="id"
    v-loadmore="TestLoadMore"
    @change="change"
    @visible-change="visibleChange"
  >
    <div v-if="nowQuery">
      <el-option
        v-for="(item, index) in (searchOptions.concat(value))"
        :key="index"
        :label="item.title"
        :value="item"
      ></el-option>
    </div>
    <div v-else>
      <el-option v-for="(item, index) in options" :key="index" :label="item.title" :value="item"></el-option>
    </div>
    {{nowQuery}}
  </el-select>
</template>
<script>
module.exports = {
  data() {
    return {
      // 默认选择arr
      options: [],
      // 选择后的arr
      value: [],
      // 当前的输入字段
      nowQuery: "",
      // 当前页
      nowPage: 1,
      // 搜索页
      searchPage: 1,
      // 搜索arr
      searchOptions: []
    };
  },
  created() {
    // 初始化
    const page = this.nowPage;
    http(config.url + "api/v1/test", "POST", {
      search: "",
      page_size: 10,
      page
    }).then(pos => {
      const list = pos.data.data;
      this.options = list.data;
      console.log(list.data, "list.data");
    });
  },
  mounted() {
    console.log(this.$refs.select)
  },
  methods: {
    // 根据搜索词加载
    TestLoadMore() {
      // console.log(this.nowQuery?++this.searchPage:++this.nowPage, 'this.nowQuery?++this.searchPage:++this.nowPage')
      http(config.url + "api/v1/test", "POST", {
        search: this.nowQuery,
        page_size: 10,
        page: this.nowQuery ? ++this.searchPage : ++this.nowPage
      }).then(pos => {
        const list = pos.data.data;
        this.nowQuery
          ? (this.searchOptions = this.searchOptions.concat(list.data))
          : (this.options = this.options.concat(list.data));
        console.log(list.data, "list.data");
      });
    },
    // 搜索
    TestRemoteMethod(query) {
      this.searchPage = 1;
      this.searchOptions = [];
      this.nowQuery = query;
      http(config.url + "api/v1/test", "POST", {
        search: query,
        page_size: 10,
        page: this.searchPage
      }).then(pos => {
        const list = pos.data.data;
        this.searchOptions = this.searchOptions.concat(list.data);
        console.log(pos, "pos");
        // console.log(list.data, "list.data");
      });
    },
    change(changeArr) {
      this.options = Array.from(new Set(this.options.concat(changeArr)))
      console.log(this.options, 'options')
    },
    visibleChange(bl){
      if(!bl){
        this.nowQuery = ''
      }
    }
  }
};
</script>